<template>
  <div class="container">
    <!-- 三级分类全局组件 -->
    <Category class="category" :scene="scene"></Category>
    <!-- 表格 -->
    <div class="table-box" v-show="scene === 0">
      <div class="addButton">
        <el-button
          type="primary"
          size="default"
          icon="Plus"
          @click="addAttr"
          :disabled="categoryStore.c3Id ? false : true"
        >
          添加平台属性
        </el-button>
      </div>
      <div class="two-box">
        <el-table class="two-table" border :data="attrArr">
          <el-table-column
            label="序号"
            width="80px"
            type="index"
            align="center"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            prop="attrName"
            width="140"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #default="scope">
              <el-tag
                style="margin: 5px"
                v-for="item in scope.row.attrValueList"
                :key="item.id"
              >
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="属性值操作" width="160">
            <template #default="scope">
              <el-button
                type="warning"
                size="small"
                icon="Edit"
                @click="updateAttr(scope.row)"
              ></el-button>
              <el-popconfirm
                :title="`你确定删除${scope.row.attrName}?`"
                width="200px"
                @confirm="deleteAttr(scope.row.id)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="small"
                    icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 展示添加或者修改屬性的div -->
    <div class="three-box" v-show="scene === 1">
      <el-form :inline="true">
        <el-form-item label="属性名称">
          <el-input
            placeholder="请你输入属性名称"
            v-model="attrParams.attrName"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="buttons">
        <el-button
          :disabled="attrParams.attrName ? false : true"
          type="primary"
          size="default"
          icon="Plus"
          @click="addAttrValue"
        >
          添加属性值
        </el-button>
        <el-button size="default" @click="cancel">取消</el-button>
      </div>
      <el-table
        border
        style="margin: 10px 0; flex: 1"
        :data="attrParams.attrValueList"
      >
        <el-table-column
          label="序号"
          width="80"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column label="属性值名称">
          <template #default="scope">
            <el-input
              :ref="(vc: any) => (inputArr[scope.$index] = vc)"
              v-if="scope.row.flag"
              placeholder="请你输入属性值名称"
              v-model="scope.row.valueName"
              @blur="toLook(scope.row, scope.$index)"
            ></el-input>
            <div v-else @click="toEdit(scope.row, scope.$index)">
              {{ scope.row.valueName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="属性值操作">
          <template #default="scope">
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              @click="attrParams.attrValueList.splice(scope.$index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="buttons">
        <el-button
          type="primary"
          size="default"
          @click="save"
          :disabled="attrParams.attrValueList.length > 0 ? false : true"
        >
          保存
        </el-button>
        <el-button size="default" @click="cancel">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  reqAttr,
  reqAddOrUpdateAttr,
  reqRemoveAttr,
} from "../../../api/product/attr/index";
import type {
  AttrResponseData,
  Attr,
  AttrValue,
} from "../../../api/product/attr/type";
import useCategoryStore from "../../../store/modules/category";
import { watch, ref, reactive, nextTick } from "vue";
import { ElMessage } from "element-plus";

const categoryStore = useCategoryStore();

const attrArr = ref<Attr[]>([]);
const scene = ref<number>(0);
const inputArr = ref<any>([]);

const attrParams = reactive<Attr>({
  attrName: "",
  attrValueList: [],
  categoryId: "",
  categoryLevel: 3,
});

// 监听三级分类的id去获取已有属性的值
watch(
  () => categoryStore.c3Id,
  () => {
    //保证三级分类得有才能发请求
    if (!categoryStore.c3Id) {
      attrArr.value = [];
      return;
    }
    getAttr();
  },
);
const getAttr = async () => {
  // 获取分类id
  const { c1Id, c2Id, c3Id } = categoryStore;
  let res: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id);
  if (res.code === 200) {
    attrArr.value = res.data;
  }
};

// 添加平台属性
const addAttr = () => {
  Object.assign(attrParams, {
    attrName: "",
    attrValueList: [],
    categoryId: categoryStore.c3Id, //点击这个按钮的时候手机新增属性的三级分类的ID
    categoryLevel: 3,
  });
  //切换为添加与修改属性的结构
  scene.value = 1;
};

// 更新
const updateAttr = (row: Attr) => {
  scene.value = 1;
  // 将已有的属性对象赋值给attrParams对象即为
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)));
};
// 删除
const deleteAttr = async (attrId: number) => {
  let res: any = await reqRemoveAttr(attrId);
  if (res.code === 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    getAttr();
  } else {
    ElMessage({
      type: "error",
      message: "删除失败",
    });
  }
};

//
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: "",
    flag: true,
  });
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  });
};

const toLook = (row: AttrValue, $index: number) => {
  if (row.valueName.trim() === "") {
    attrParams.attrValueList.splice($index, 1);
    ElMessage({
      type: "error",
      message: "属性值不能为空",
    });
    return;
  }
  let repeat = attrParams.attrValueList.find((item: any) => {
    if (item !== row) {
      return item.valueName === row.valueName;
    }
  });
  if (repeat) {
    attrParams.attrValueList.splice($index, 1);
    ElMessage({
      type: "error",
      message: "属性值不能重复",
    });
    return;
  }
  row.flag = false;
};
const toEdit = (row: AttrValue, $index: number) => {
  row.flag = true;
  nextTick(() => {
    inputArr.value[$index].focus();
  });
};
// 保存
const save = async () => {
  let res: any = await reqAddOrUpdateAttr(attrParams);
  if (res.code === 200) {
    scene.value = 0;
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改成功" : "添加成功",
    });
    getAttr();
  } else {
    ElMessage({
      type: "error",
      message: attrParams.id ? "修改失败" : "添加失败",
    });
  }
};
// 取消
const cancel = () => {
  scene.value = 0;
};
</script>

<style scoped lang="scss">
.container {
  height: 100%;
  width: 100%;
  padding: 10px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-sizing: border-box;
  // box-shadow: var(--el-box-shadow-light);// card阴影

  .category {
    height: 90px;
    width: 100%;
    box-sizing: border-box;
  }

  .table-box {
    margin: 10px 0 0 0;
    padding: 20px;
    flex: 1;
    box-sizing: border-box;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    box-shadow: var(--el-box-shadow-light); // card阴影
    border-radius: 5px;

    .addButton {
      height: 40px;
      width: 100%;
      margin-bottom: 10px;
      padding: 3px 0;
      box-sizing: border-box;
    }

    .two-box {
      flex: 1;
      box-sizing: border-box;
      overflow: hidden;

      // 表格的样式
      .two-table {
        height: 100%;
        width: 100%;
      }
    }
  }

  .three-box {
    flex: 1;
    padding: 20px;
    border-radius: 5px;
    height: auto;
    margin-top: 10px;
    max-height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    box-shadow: var(--el-box-shadow-light); // card阴影

    .buttons {
      height: 35px;
    }
  }
}
</style>
